<template>
  <el-card style="height: 86vh">
    <el-row>
      <el-col>
        <el-date-picker
            v-model="gkDate"
            type="date"
            @change="handleTimePickChange"
            value-format="YYYY-MM-DD"
            format="YYYY年MM月DD日"
            placeholder="选择日期">
        </el-date-picker>
      </el-col>
    </el-row>

    <el-input type="textarea" style="margin-top: 20px" :rows="16" v-model="gkDesc"
              v-loading="dataLoading"></el-input>
    <el-button type="primary" style="margin-top: 20px"  @click="copy">复制</el-button>
  </el-card>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import utils from '@/utils/utils'
import store from '@/store'
import {createDailyData, getAll, getGkDatawx,getGkData, getLastDatTime} from '@/api/work-order'
import { isSameDate } from '@/utils/common'

let headers = {}
const upLoadLoading = ref(false)
const UploadExcelDialogShow = ref(false)
const total = ref(0)
const page = ref(1)
const size = ref(10)
const tableData = ref([])
const dataLoading = ref(false)
const selectTimeDialogShow = ref(false)
const timeModelValue = ref('')
const gkDate = ref('')
const gkDesc = ref('')

const truncateString = (str, maxLength = 10) => {
  if (str.length > maxLength) {
    return str.substring(0, maxLength) + '...';
  }
  return str;
}

const getData = async () => {
  dataLoading.value = true
  const result = await getGkData({
    time: gkDate.value
  })
  gkDesc.value = generateDailyReport(result,  gkDate.value)
  dataLoading.value = false
}

const getTime = async () => {
  gkDate.value = (await getLastDatTime()).substring(0, 10)
}
getTime().then(() => {
  getData()
})

const handleProgress = (file) => {
  upLoadLoading.value = true
}

const beforeUploadHandle = (file) => {
  utils.showLoadding('正在上传...')
  return true
}

const handleSuccess = async (res) => {
  if (res.content === 0) {
    utils.showSuccess('上传数据成功')
  }

  UploadExcelDialogShow.value = false
  utils.hideLoadding()
}
const handleTimePickChange = (value) => {
  if (value===null) return
  gkDate.value = value
  getData()
}
const copy = () => {
  navigator.clipboard.writeText(gkDesc.value)
  utils.showSuccess('复制成功')
}

function generateDailyReport(data, dateStr) {
  const date = new Date(dateStr);
  const dateText = `${date.getMonth() + 1}月${date.getDate()}日`;

  // 工具函数
  // const groupBy = (arr, key) => arr.reduce((acc, item) => {
  //   (acc[item[key]] = acc[item[key]] || []).push(item);
  //   return acc;
  // }, {});

  // const summarize = (arr) => arr.map(item => `${item.cityBureau}${item.num > 1 ? item.num + '宗' : '1宗'}`).join('、');

  const summarizeBusiness = (arr) => arr.sort((a, b) => b.sum - a.sum).map(item => `${item.businessName}${item.sum}宗`).join('，');
  //自定义工具
  
function formatArray95598(array) {
  // 按num降序排序
  const sorted = [...array].sort((a, b) => b.num - a.num);
  // 按num和age分组并格式化
  const result = [];
  let currentNum = null;
  let normalGroup = [];
  let sameUserGroup = [];
  
  for (const item of sorted) {
    // 如果num变化，处理上一组数据
    if (currentNum !== null && item.num !== currentNum) {
      result.push(formatGroup(currentNum, normalGroup, sameUserGroup));
      normalGroup = [];
      sameUserGroup = [];
    }
    currentNum = item.num;
    // 根据isSameUser分组
    if (item.isSameUser === 1) {
      sameUserGroup.push(item.cityBureau);
    } else {
      normalGroup.push(item.cityBureau);
    }
  }
  
  // 处理最后一组
  if (currentNum !== null) {
    result.push(formatGroup(currentNum, normalGroup, sameUserGroup));
  }
  
  return result.filter(Boolean).join('，');
}
/**
 * 格式化单个分组
 */
function formatGroup(num, normalNames, sameUserNames) {
  const formattedParts = [];
  
  // 处理普通组
  if (normalNames.length > 0) {
    const uniqueNames = [...new Set(normalNames)];
    let part = uniqueNames.length === 1 
      ? `${uniqueNames[0]}${num}宗` 
      : `${uniqueNames.join('、')}各${num}宗`;
      // console.log(,"222222");
    // 添加亮红灯标识
    // if (num > 3) {
    //   part += "亮红灯";
    // }
    formattedParts.push(part);
  }
  // 处理同一用户组
  if (sameUserNames.length > 0) {
    const uniqueNames = [...new Set(sameUserNames)];
    formattedParts.push(`${uniqueNames.join('、')}各${num}宗（同一用户）`);
  }
  
  return formattedParts.join('，');
}
function formatGroupBusiness(sum, normalNames, sameUserNames) {
  const formattedParts = [];
  // 处理普通组
  if (normalNames.length > 0) {
    const uniqueNames = [...new Set(normalNames)];
    let part = uniqueNames.length === 1 
      ? `${uniqueNames[0]}${sum}宗` 
      : `${uniqueNames.join('、')}各${sum}宗`;
    formattedParts.push(part);
  }
  // 处理同一用户组
  if (sameUserNames.length > 0) {
    const uniqueNames = [...new Set(sameUserNames)];
    formattedParts.push(`${uniqueNames.join('、')}各${sum}宗（同一用户）`);
  }
  return formattedParts.join('，');
}
function formatArray12398(array) {
  return Object.entries(
    array.sort((a, b) => b.num - a.num)
      .reduce((acc, { cityBureau, num, isSameUser }) => {
        const key = `${num}-${isSameUser}`;
        acc[key] = (acc[key] || new Set()).add(cityBureau);
        return acc;
      }, {})
  )
  .sort(([a], [b]) => b.split('-')[0] - a.split('-')[0])
  .map(([key, names]) => {
    const [num, isSameUser] = key.split('-');
    const nameList = [...names].join('、');
    const base = names.size === 1 
      ? `${nameList}${num}宗` 
      : `${nameList}各${num}宗`;
    return isSameUser === '1' 
      ? `${base}同一用户` 
      : num >= 3 ? `${base}（亮红灯）` : base;
  })
  .join('，');
  // 按num值从大到小排序
}
//主要反映12398
function formatdetail12398Business(array) {
   return Object.entries(
    array.reduce((acc, { businessName, sum }) => {
      acc[sum] = (acc[sum] || new Set()).add(businessName);
      return acc;
    }, {})
  )
  .sort(([a], [b]) => b - a) // 按num从大到小排序
  .map(([sum, names]) => 
    [...names].length === 1 
      ? `${[...names]}${sum}宗` 
      : `${[...names].join('、')}各${sum}宗`
  )
  .join('，');
}
//12398申诉处理
function formatArray12398Complaint(array) {
  return Object.entries(
    array.sort((a, b) => b.num - a.num)
      .reduce((acc, { cityBureau, num, isSameUser }) => {
        const key = `${num}-${isSameUser}`;
        acc[key] = (acc[key] || new Set()).add(cityBureau);
        return acc;
      }, {})
  )
  .sort(([a], [b]) => b.split('-')[0] - a.split('-')[0])
  .map(([key, names]) => {
    const [num, isSameUser] = key.split('-');
    const nameList = [...names].join('、');
    const base = names.size === 1 
      ? `${nameList}${num}宗` 
      : `${nameList}各${num}宗`;
    return isSameUser === '1' 
      ? `${base}同一用户` 
      : num >= 3 ? `${base}` : base;
  })
  .join('，');
  // 按num值从大到小排序
}

  // 一次投诉统计
  const detail95598Total = data.detail95598.reduce((sum, d) => sum + d.num, 0);
  const detail95598Text = detail95598Total > 0
      ? `新增95598一次投诉${detail95598Total}宗，分别为${formatArray95598(data.detail95598)}；主要反映${formatdetail12398Business(data.detail95598Business)}。`
      : `无新增95598一次投诉。`;
  const detail95598TimeoutTotal = data.detail95598Timeout.reduce((num, d) => num + d.num, 0);
  const detail95598TimeoutText = data.detail95598Timeout.length > 0
      ? `新增${detail95598TimeoutTotal}宗超时未处置工单，为${formatArray95598(data.detail95598Timeout)}。`
      : `无新增超时未处置工单。`;

  const detail95598RepeatText = data.detail95598Repeat.length > 0
      ? `新增${data.detail95598Repeat.length}宗95598重复投诉工单，为${formatArray95598(data.detail95598Repeat)}；主要为${formatdetail12398Business(data.detail95598RepeatBusiness)}。`
      : `无新增95598重复投诉工单。`;

  // 12398统计
  const detail12398Total = data.detail12398.reduce((sum, d) => sum + d.num, 0);
  const detail12398Text = detail12398Total > 0
      ? `新增12398转办投诉${detail12398Total}宗，分别为${formatArray12398(data.detail12398)}；主要反映${formatdetail12398Business(data.detail12398Business)}。`
      : `无新增12398转办投诉。`;
  const detail12398ComplaintTotal = data.detail12398Complaint.reduce((sum, d) => sum + d.num, 0);
  const detail12398ComplaintText = data.detail12398Complaint.length > 0
      ? `新增${detail12398ComplaintTotal}宗12398投诉申诉，为${formatArray12398Complaint(data.detail12398Complaint)}。`
      : `无新增12398投诉申诉。`;

  return `诉求管控日报（${dateText}）\n1.${detail95598Text}${detail95598RepeatText}${detail95598TimeoutText}\n2.${detail12398Text}${detail12398ComplaintText}`;
}

onMounted(() => {
  headers = { 'X-Token': store.getters.token }
})
</script>
